#!/usr/bin/env python
# -*- coding: utf-8 -*-

#    This file is part of My Text Editor.
#
#    My Text Editor is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    My Text Editor is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with My Text Editor.  If not, see <http://www.gnu.org/licenses/>.

# Copyright (C) 2013 Joseba García Etxebarria <joseba.gar@gmail.com>. All rights reserved.         

"""This is the main dialog code for my text editor.
    The interface itself is holded in dialog_main.ui"""

import os,sys,subprocess

# Import Qt modules
from PyQt4 import QtCore,QtGui

# Import the compiled UI module
from linetextwidget import LineTextWidget
from ui_mainwindow import Ui_MainWindow
from preferences import preferences
from dialog_preferences import dialog_preferences

# Create a class for our main window
class dialog_main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # This is always the same
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)

        # Connect the signals
        self.ui.actionNew.triggered.connect(self.new_file)
        self.ui.actionOpen.triggered.connect(self.dialog_open_file)
        self.ui.actionSave.triggered.connect(self.save_file)
        self.ui.actionClose.triggered.connect(self.close_current_tab)
        self.ui.buttonNew.clicked.connect(self.new_file)
        self.ui.buttonOpen.clicked.connect(self.dialog_open_file)
        self.ui.buttonSave.clicked.connect(self.save_file)
        self.ui.actionPreferences.triggered.connect(self.show_preferences)
        self.ui.actionQuit.triggered.connect(sys.exit)
        self.ui.tabWidget.tabCloseRequested.connect(self.close_tab)
        self.ui.tabWidget.tabBar().tabMoved.connect(self.tabmoved)
        self.ui.tabWidget.currentChanged.connect(self.set_title)

        # List of tabs
        self.files = []     # Actually, this is just a shorthand and is not really needed
        self.edits = []

        # Initialize the preferences, grab Nastran dir
        self.prefs          = preferences()
        self.nastrandir     = self.prefs.get('nastrandir')
        self.nastranlibrary = self.prefs.get('nastranlibrary')

        # Determine the open program based on current platform
        self.opencommand = ''
        if sys.platform.startswith('win'):
            self.opencommand = 'start'
        elif sys.platform.startswith('darwin'):
            self.opencommand = 'open'
        elif sys.platform.startswith('linux'):
            self.opencommand = 'xdg-open'

        # Add a link in the Help menu to the Nastran library, if available
        if os.path.isfile( self.nastranlibrary ):
            action = QtGui.QAction(self)
            action.setObjectName('Nastran library')
            action.setText('Nastran &Library')
            action.triggered.connect(self.open_nastranlibrary)
            self.ui.menuHelp.addAction(action)

    def open_nastranlibrary(self, card=''):
        'Open the Nastran Library'
        if os.path.isfile( self.nastranlibrary ):
            if card:
                subprocess.Popen([self.opencommand, self.nastranlibrary+'#'+card])
                #os.system(self.opencommand+' '+self.nastranlibrary+'#'+card)
            else:
                #os.system(self.opencommand+' '+self.nastranlibrary)
                subprocess.Popen([self.opencommand, self.nastranlibrary])
        #self.statusBar().showMessage("Ouya")
    
    def show_preferences(self):
        'Displays the preferences dialog'
        dialog=dialog_preferences()

    def new_file(self):
        'Create a new empty file and open a new tab'
        tab = QtGui.QWidget()
        verticalLayout = QtGui.QVBoxLayout(tab)
        textEdit = LineTextWidget(tab)
        textEdit.edit.main_dialog = self
        verticalLayout.addWidget(textEdit)
        i = self.ui.tabWidget.addTab(tab, '[New File]')
        self.ui.tabWidget.setCurrentIndex(i)
        self.edits.append(textEdit)
    
    def save_file(self):
        'Save the currently open tab'
        index = self.ui.tabWidget.currentIndex()
        if index >= 0:
            self.statusBar().showMessage("Saved", 500)
            with open(self.files[index],'w') as fd:
                fd.write(self.edits[index].getTextEdit().toPlainText())

    def open_file(self, path):
        'Open file in given path in a new tab'
        if os.path.isfile(path) and not path in self.files:
            tab = QtGui.QWidget()
            verticalLayout = QtGui.QVBoxLayout(tab)
            textEdit = LineTextWidget(tab)
            textEdit.edit.main_dialog = self
            verticalLayout.addWidget(textEdit)
            textEdit.load_file(path)
            i = self.ui.tabWidget.addTab(tab, os.path.basename(path))
            self.ui.tabWidget.setCurrentIndex(i)
            self.files.insert(i, path)
            self.edits.insert(i, textEdit)
            self.setWindowTitle("Joseba's BlockEditor - {0}".format(path))

    def dialog_open_file(self):
        'Show open file dialog and open it'
        # Open File dialog should be pointed to the dir holding the current file
        dirname = ''
        index = self.ui.tabWidget.currentIndex()
        if index >= 0:
            dirname = self.edits[index].dirname
        path = QtGui.QFileDialog.getOpenFileName(self, "Choose Nastran file",
                                               dirname,
                                               "Nastran models (*.dat *.bdf *.blk);;DMAP files (*.dmap)");
        path = str(path)
        self.open_file(path)

    def close_current_tab(self):
        'Close current tab'
        index = self.ui.tabWidget.currentIndex()
        if index >= 0:
            self.edits.pop(index)
            self.files.pop(index)
            layout = self.ui.tabWidget.currentWidget().layout()
            self.clearLayout(layout)
            self.ui.tabWidget.removeTab(index)

    def close_tab(self, index):
        'Close tab number index'
        current = self.ui.tabWidget.currentIndex()
        self.ui.tabWidget.setCurrentIndex(index)
        self.close_current_tab()
        if index < current:
            self.ui.tabWidget.setCurrentIndex(index)
        else:
            self.ui.tabWidget.setCurrentIndex(index-1)
    
    def tabmoved(self,  index_from,  index_to):
        'Update the table of open tabs, so that we can keep track of the edits and open files'
        edit = self.edits.pop(index_from)
        self.edits.insert(index_to,  edit)
        path = self.files.pop(index_from)
        self.files.insert(index_to,  path)
    
    def set_title(self, index):
        try:
            self.setWindowTitle("Joseba's BlockEditor - {0}".format(self.files[index]))
        except IndexError:
            pass

    def clearLayout(self, layout):
        'Clear all the elements in a QLayout'
        
        for i in reversed(range(layout.count())):
            item = layout.itemAt(i)

            if isinstance(item, QtGui.QWidgetItem):
                item.widget().deleteLater()
            else:
                print('Deleting sub-layout\n')
                self.clearLayout(item.layout())

            # remove the item from layout
            layout.removeItem(item)



